import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import { Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material'
import useWatch from '../../Hook/useWatch'
import PropsType from "prop-types";

const DialogComponents = (props) => {
  const { t } = useTranslation()

  const handleClose = (event) => {
    if (props.closeOnClickModel || !event) {
      props.handleClose()
    }
  }
  const handleConfirm = () => {
    props.handleConfirm()
  }
  useWatch(props.open, (newOpen, oldOpen) => { // 监听打开弹窗事件
    if (newOpen && !oldOpen && typeof(props.opened) === 'function') { // 当上一次状态是关闭并且新的状态是打开时触发事件
      props.opened()
    }
  })
  return (
    <div>
      <Dialog open={props.open} onClose={handleClose} maxWidth="xl" disableEscapeKeyDown>
        <DialogTitle>
          {props.dialogTitle}
        </DialogTitle>
        <DialogContent dividers style={{width: props.width ? props.width : '32.5rem', height: props.height ? props.height : '20rem'}}>
          {props.children}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => handleClose()}>{t('common.cancel')}</Button>
          {
            props.noShowConfirm ? undefined : <Button onClick={() => handleConfirm()} variant="contained" disabled={props.isSubmitting}>{t('common.confirm')}</Button>
          }
        </DialogActions>
      </Dialog>
    </div>
  )
}

DialogComponents.propTypes = {
  opened: PropsType.func,
  open: PropsType.bool.isRequired,
  noShowConfirm: PropsType.bool,
  handleClose: PropsType.func.isRequired,
  handleConfirm: PropsType.func,
  closeOnClickModel: PropsType.bool,
  width: PropsType.string,
  height: PropsType.string,
  dialogTitle: PropsType.string.isRequired
}

DialogComponents.defaultProps = {
  opened: () => {},
  noShowConfirm: false,
  handleConfirm: () => {},
  closeOnClickModel: true
}

export default memo(DialogComponents)